<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRouterPush } from '@/hooks/common/router';
import { batchDeleteMappingSets, deleteMappingSet, fetchMappingSetList } from '@/service/api/product-model-mapping';
import { createDataset } from '@/service/api/dataset';

// 路由跳转
const { routerPushByKey } = useRouterPush();

// 数据状态
const loading = ref(false);
const mappingSetList = ref<Api.ProductModelMapping.MappingSet[]>([]);
const selectedRowKeys = ref<string[]>([]);

// 表格列定义
const columns = [
  {
    title: '映射集ID',
    dataIndex: 'id',
    key: 'id',
    width: 100
  },
  {
    title: '映射集名称',
    dataIndex: 'name',
    key: 'name',
    width: 200
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '产品数量',
    dataIndex: 'productCount',
    key: 'productCount',
    width: 100,
    align: 'center' as const
  },
  {
    title: '模型数量',
    dataIndex: 'modelCount',
    key: 'modelCount',
    width: 100,
    align: 'center' as const
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    align: 'center' as const
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center' as const
  }
];

// 加载映射集列表
async function loadMappingSetList() {
  try {
    loading.value = true;
    const response = await fetchMappingSetList();
    console.log('response', response);

    if (response?.data) {
      // 后端返回的data直接是数组，不是包含list的对象
      mappingSetList.value = Array.isArray(response.data) ? response.data : response.data.list || [];
    } else {
      // 如果API未实现，使用模拟数据
      mappingSetList.value = [
        {
          id: '1',
          name: '债券产品映射集',
          description: '包含所有债券类产品的模型映射关系',
          productCount: 15,
          modelCount: 8,
          createTime: '2024-01-15 10:30:00',
          status: 'active' as const
        },
        {
          id: '2',
          name: '期权产品映射集',
          description: '包含所有期权类产品的模型映射关系',
          productCount: 12,
          modelCount: 6,
          createTime: '2024-01-20 14:20:00',
          status: 'active' as const
        },
        {
          id: '3',
          name: '利率互换映射集',
          description: '包含所有利率互换产品的模型映射关系',
          productCount: 8,
          modelCount: 4,
          createTime: '2024-01-25 09:15:00',
          status: 'inactive' as const
        }
      ];
    }
  } catch (error) {
    console.error('加载映射集列表失败:', error);
    // 发生错误时使用模拟数据
    mappingSetList.value = [
      {
        id: '1',
        name: '债券产品映射集',
        description: '包含所有债券类产品的模型映射关系',
        productCount: 15,
        modelCount: 8,
        createTime: '2024-01-15 10:30:00',
        status: 'active' as const
      }
    ];
    window.$message?.warning('API未实现，使用模拟数据');
  } finally {
    loading.value = false;
  }
}

// 查看映射集详情
function viewMappingSetDetail(record: any) {
  routerPushByKey('valuation_product-tree', {
    query: {
      mappingSetId: record.id,
      mappingSetName: record.name
    }
  });
}

// 模态框相关状态
const modalVisible = ref(false);
const modalLoading = ref(false);
const formData = ref({
  id: '',
  name: '',
  description: ''
});

// 创建新映射集
function createMappingSet() {
  modalVisible.value = true;
  formData.value = {
    id: '',
    name: '',
    description: ''
  };
}

// 保存映射集
async function handleSaveMappingSet() {
  console.info('formData.value', formData.value);
  if (!formData.value.id.trim()) {
    window.$message?.error('请输入映射集ID');
    return;
  }
  if (!formData.value.name.trim()) {
    window.$message?.error('请输入映射集名称');
    return;
  }

  modalLoading.value = true;
  try {
    const { data: resData, error: err } = await createDataset({
      id: formData.value.id.trim(),
      name: formData.value.name.trim(),
      description: formData.value.description.trim() || undefined,
      status: '1',
      enabled: true
    });

    if (resData && !err) {
      window.$message?.success('创建映射集成功');
      modalVisible.value = false;
      await loadMappingSetList();
    }
  } catch (error) {
    console.error('创建映射集失败:', error);
  } finally {
    modalLoading.value = false;
  }
}

// 取消创建
function handleCancelCreate() {
  modalVisible.value = false;
  formData.value = {
    id: '',
    name: '',
    description: ''
  };
}

// 编辑映射集
function editMappingSet(_record: any) {
  // 实现编辑映射集功能
  window.$message?.info('编辑映射集功能开发中...');
}

// 删除映射集
async function handleDeleteMappingSet(record: any) {
  try {
    await deleteMappingSet(record.id);
    window.$message?.success('删除映射集成功');
    await loadMappingSetList();
  } catch (error) {
    console.error('删除映射集失败:', error);
    window.$message?.error('删除映射集失败');
  }
}

// 批量删除
async function batchDelete() {
  if (selectedRowKeys.value.length === 0) {
    window.$message?.warning('请选择要删除的映射集');
    return;
  }

  try {
    await batchDeleteMappingSets(selectedRowKeys.value);
    window.$message?.success('批量删除成功');
    selectedRowKeys.value = [];
    await loadMappingSetList();
  } catch (error) {
    console.error('批量删除失败:', error);
    window.$message?.error('批量删除失败');
  }
}

// 表格行选择
const rowSelection = {
  selectedRowKeys,
  onChange: (keys: string[]) => {
    selectedRowKeys.value = keys;
  }
};

onMounted(() => {
  loadMappingSetList();
});
</script>

<template>
  <div class="product-model-mapping-list">
    <ACard title="产品-模型映射集管理">
      <template #extra>
        <ASpace>
          <AButton type="primary" @click="createMappingSet">
            <template #icon>
              <icon-carbon:add />
            </template>
            新建映射集
          </AButton>
          <AButton danger :disabled="selectedRowKeys.length === 0" @click="batchDelete">
            <template #icon>
              <icon-carbon:delete />
            </template>
            批量删除
          </AButton>
          <AButton @click="loadMappingSetList">
            <template #icon>
              <icon-carbon:renew />
            </template>
            刷新
          </AButton>
        </ASpace>
      </template>

      <ATable
        :columns="columns"
        :data-source="mappingSetList"
        :loading="loading"
        :row-selection="rowSelection as any"
        :pagination="{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total: number) => `共 ${total} 条记录`
        }"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <ATag :color="record.status === 'active' ? 'green' : 'red'">
              {{ record.status === 'active' ? '启用' : '禁用' }}
            </ATag>
          </template>

          <template v-else-if="column.key === 'action'">
            <ASpace>
              <AButton type="link" size="small" @click="viewMappingSetDetail(record)">
                <template #icon>
                  <icon-carbon:view />
                </template>
                查看详情
              </AButton>
              <AButton type="link" size="small" @click="editMappingSet(record)">
                <template #icon>
                  <icon-carbon:edit />
                </template>
                编辑
              </AButton>
              <APopconfirm
                title="确定要删除这个映射集吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDeleteMappingSet(record)"
              >
                <AButton type="link" size="small" danger>
                  <template #icon>
                    <icon-carbon:delete />
                  </template>
                  删除
                </AButton>
              </APopconfirm>
            </ASpace>
          </template>
        </template>
      </ATable>
    </ACard>

    <!-- 新建映射集模态框 -->
    <AModal
      v-model:open="modalVisible"
      title="新建映射集"
      :confirm-loading="modalLoading"
      @ok="handleSaveMappingSet"
      @cancel="handleCancelCreate"
    >
      <AForm :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <AFormItem label="映射集ID" required>
          <AInput v-model:value="formData.id" placeholder="请输入映射集ID" :maxlength="50" />
        </AFormItem>
        <AFormItem label="映射集名称" required>
          <AInput v-model:value="formData.name" placeholder="请输入映射集名称" :maxlength="100" />
        </AFormItem>
        <AFormItem label="描述">
          <ATextarea v-model:value="formData.description" placeholder="请输入映射集描述" :rows="3" :maxlength="500" />
        </AFormItem>
      </AForm>
    </AModal>
  </div>
</template>

<style scoped>
.product-model-mapping-list {
  padding: 16px;
}
</style>
